import axios from "axios";
import { showApiError } from "@/utils";

// 创建一个axios实例（可选，但推荐，以便配置全局设置）
const apiClient = axios.create({
  baseURL: "/api", // 你的API基础URL
  timeout: 300000, // 请求超时时间
  headers: {
    "Content-Type": "application/json",
    // 其他需要的全局头信息
  },
});

// 辅助函数：发送GET请求
export const get = async (url, params, defaultVal = null) => {
  try {
    const response = await apiClient.get(url, {
      params,
    });
    const { error } = response?.data;
    if (error) {
      showApiError(error);
      return defaultVal;
    }
    return response?.data?.result || response?.data || response; // 返回响应数据
  } catch (error) {
    showApiError(error);
    return defaultVal;
  }
};

// 辅助函数：发送POST请求
export const post = async (url, data, defaultVal = null) => {
  try {
    const response = await apiClient.post(url, data);
    const { error } = response?.data;
    if (error) {
      showApiError(error);
      return defaultVal;
    }
    return response?.data?.result || response?.data || response; // 返回响应数据
  } catch (error) {
    showApiError(error);
    return defaultVal;
  }
};

export const del = async (url) => {
  try {
    const response = await apiClient.delete(url);
    const { error } = response?.data;
    if (error) {
      showApiError(error);
    }
  } catch (error) {
    showApiError(error);
  }
};
